package com.campus.counseling.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.campus.counseling.entity.SysLoginLog;
import com.campus.counseling.security.SecurityUser;
import com.campus.counseling.model.mapper.SysLoginLogMapper;
import com.campus.counseling.util.HttpClient;
import com.campus.counseling.util.UserAgentAnalyzer;
import com.campus.counseling.util.SecurityUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final SysLoginLogMapper loginLogMapper;
    private final UserAgentAnalyzer userAgentAnalyzer;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取当前登录用户
        SecurityUser securityUser = SecurityUtils.getLoginUser();
        if (securityUser != null) {
            // 记录登录日志
            SysLoginLog loginLog = new SysLoginLog();
            loginLog.setUserId(securityUser.getId());
            
            // 获取IP地址
            String ipAddress = getIpAddress(request);
            loginLog.setIp(ipAddress);
            
            // 获取地理位置
            String location = getLocationByIp(ipAddress);
            loginLog.setLocation(location);
            
            // 获取User-Agent信息
            String userAgentString = request.getHeader("User-Agent");
            UserAgent agent = userAgentAnalyzer.parseUserAgent(userAgentString);
            
            // 设置浏览器信息
            loginLog.setBrowser(userAgentAnalyzer.getBrowserInfo(agent));
            
            // 设置操作系统信息
            loginLog.setOs(userAgentAnalyzer.getOperatingSystem(agent));
            
            // 设置设备类型
            loginLog.setDeviceType(userAgentAnalyzer.getDeviceType(agent));
            
            loginLog.setStatus(0); // 成功
            loginLog.setMsg("登录成功");
            loginLog.setCreateTime(LocalDateTime.now());
            loginLog.setLoginDuration(0); // 初始登录时长为0
            loginLog.setUserAgent(userAgentString);
            
            // 保存登录日志
            loginLogMapper.insert(loginLog);
        }
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                              Object handler, Exception ex) {
        // 更新登录时长和退出时间
        SecurityUser securityUser = SecurityUtils.getLoginUser();
        if (securityUser != null) {
            // 查找最近的登录记录
            SysLoginLog lastLog = loginLogMapper.selectOne(
                new LambdaQueryWrapper<SysLoginLog>()
                    .eq(SysLoginLog::getUserId, securityUser.getId())
                    .eq(SysLoginLog::getLoginDuration, 0)
                    .orderByDesc(SysLoginLog::getCreateTime)
                    .last("LIMIT 1")
            );
            
            if (lastLog != null) {
                LocalDateTime now = LocalDateTime.now();
                // 计算登录时长（秒）
                long duration = ChronoUnit.SECONDS.between(lastLog.getCreateTime(), now);
                
                // 更新登录时长和退出时间
                loginLogMapper.update(null, 
                    new LambdaUpdateWrapper<SysLoginLog>()
                        .eq(SysLoginLog::getId, lastLog.getId())
                        .set(SysLoginLog::getLoginDuration, (int) duration)
                        .set(SysLoginLog::getLogoutTime, now)
                );
            }
        }
    }
    
    /**
     * 获取IP地址
     */
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    /**
     * 根据IP获取地理位置
     */
    private String getLocationByIp(String ip) {
        try {
            String url = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true";
            String response = HttpClient.get(url);
            JSONObject json = JSON.parseObject(response);
            return json.getString("pro") + " " + json.getString("city");
        } catch (Exception e) {
            return "未知";
        }
    }
} 